extends Area2D
class_name Bullet

signal  to_recycle_self()

@export var bullet_shape:CollisionShape2D

var shooter:Node2D
var velocity:Vector2
var life_timer:Timer
var mods:Array[Node]

func _ready() -> void:
	body_entered.connect(strike)

func strike(node:Node2D):
	if node is TileMapLayer:
		_recycle_self()

func _physics_process(_delta: float) -> void:
	position += velocity

func init(shooter_:Node,velocity_:Vector2,life_time:float = -1):
	velocity = velocity_
	shooter = shooter_
	rotation = velocity.angle()
	
	if life_time == -1:
		return
	_create_timer()
	life_timer.start(life_time)

func _create_timer():
	if life_timer:
		return
	life_timer = Timer.new()
	life_timer.one_shot = true
	life_timer.timeout.connect(_recycle_self)
	add_child(life_timer)

func _on_visible_on_screen_notifier_2d_screen_exited() -> void:
	_recycle_self()

func _recycle_self():
	to_recycle_self.emit()
	rotation = 0
	position = Vector2.ZERO
